<template>
  <section>
    <el-upload v-if="attachList.length < limit"
               multiple
               class="upload-box"
               :limit="uploadLength"
               :show-file-list="false"
               :headers="uploadObj.headers"
               :name="uploadObj.name"
               :action="uploadObj.serviceUrl"
               :file-list="fileList"
               :on-success="handleSuccess"
               :before-upload="beforeUpload"
               :disabled="isUploadDisabled"
               :on-change="handleOnChange"
               :on-exceed="onExceed"
               :on-error="handleError"
               :on-remove="deleteFile">
      <el-button v-if="!isDisabled"
                 size="small"
                 type="primary"
                 :class="{'noUpload': loading}"
                 :loading="loading"
                 :disabled="isUploadDisabled">点击上传</el-button>
    </el-upload>
    <span v-if="!isDisabled"
          :title="text"
          class="upload-text">附件说明：最多可上传{{ limit }}个附件，{{ text }}</span>
    <!-- 上传之后预览 -->
    <photo-gallery v-if="isCover && (attachList === undefined || attachList.length > 0)"
                   :is-disabled="isDisabled"
                   :attach-list="attachList"
                   @delete="deleteFile" />
  </section>
</template>

<script>
import txt_icon from "@static/images/txt-icon.png";
import pdf_icon from "@static/images/pdf-icon.png";
import excel_icon from "@static/images/excel-icon.png";
import word_icon from "@static/images/word-icon.png";
import zip_icon from "@static/images/zip-icon.png";
import rar_icon from "@static/images/zip.png";
import word_pic from "@static/images/word.png";
import xls_pic from "@static/images/xls.png";
import zip_pic from "@static/images/zip-pic.png";
import txt_pic from "@static/images/txt.png";
import pdf_pic from "@static/images/pdf.png";
import PhotoGallery from "./PhotoGallery.vue";

let FILE_FORMATS = ["doc", "docx", "xls", "xlsx", "pdf", "txt", "jpg", "png", "zip", "rar"];

export default {
  name: "UploadFileSelector",
  components: { PhotoGallery },
  props: {
    attachForm: Array,
    limit: {
      type: Number,
      default: 6
    },
    separate: Boolean,
    isCreate: {
      // 判断是否为下单页面
      type: Boolean,
      default: false
    },
    isContract: {
      type: Boolean,
      default: false
    },
    isCover: {
      type: Boolean,
      default: false
    },
    text: {
      type: String,
      default:
        "附件支持doc(docx)、xls(xlsx)、pdf、txt、jpg、png、zip、rar，单个文件不能大于2MB"
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    requestUrl: {
      type: String,
      default: null
    },
    isCreateOrder: {
      type: Boolean,
      default: false
    },
    fileSize: {
      type: Number,
      default: 2
    }
  },
  data () {
    return {
      txt_icon,
      pdf_icon,
      excel_icon,
      word_icon,
      zip_icon,
      rar_icon,
      word_pic,
      xls_pic,
      zip_pic,
      txt_pic,
      pdf_pic,
      fileList: [],
      attachList: [],
      putFileLength: 0,
      loading: false,
      uploadLength: 6,
      uploadObj: {
        headers: {
          // Authorization: window.sessionStorage.getItem('token')
          Authorization: "Bearer " + sessionStorage.getItem("token")
        },
        name: "file",
        serviceUrl: this.requestUrl ? `${this.$processEnvUrl}${this.requestUrl}` : `${this.$processEnvUrl}/basic/upload`
      },
      /* 图片预览list */
      srcList: []
    };
  },
  computed: {
    isUploadDisabled () {
      return this.isDisabled || this.loading || this.attachList.length >= this.limit
    },
    fileedTypes () {
      return {
        word: {
          suffixes: ["doc", "docx"],
          icon: this.word_icon
        },
        excel: {
          suffixes: ["xls", "xlsx"],
          icon: this.isCreate ? this.xls_pic : this.excel_icon
        },
        pdf: {
          suffixes: ["pdf"],
          icon: this.isCreate ? this.pdf_pic : this.pdf_icon
        },
        txt: {
          suffixes: ["txt"],
          icon: this.isCreate ? this.txt_pic : this.txt_icon
        },
        image: {
          suffixes: ["jpg", "png"],
          icon: ""
        },
        zip: {
          suffixes: ["zip", "rar"],
          icon: this.isCreate ? this.zip_pic : this.rar_icon
        }
      }
    }
  },
  watch: {
    attachForm: {
      deep: true,
      handler (data) {
        if (data) this.fileTypePic(this.attachForm);
      }
    }
  },
  created () {
    // this.attachList = this.attachForm
    if (this.attachForm) this.fileTypePic(this.attachForm);
  },
  methods: {
    caseLimit (value, comparisonValue) {
      let reg = new RegExp(comparisonValue, "gi");
      return (value.match(reg) != null) && (value.length === comparisonValue.length);
    },
    beforeUpload (file) {
      const limit = file.name.substr(file.name.lastIndexOf(".") + 1);
      const isLt2M = file.size / 1024 / 1024 < this.fileSize;

      let flag = FILE_FORMATS.some((e) => this.caseLimit(e, limit))

      if (!isLt2M) {
        this.$message({
          message: `上传文件大小不能超过${this.fileSize}MB`,
          type: "warning"
        });
        this.loading = false
        return false
      } else if (!flag) {
        this.$message.warning("请参考附件支持格式说明，上传正确文件格式");
        this.loading = false
        return false;
      }
      return true
    },
    onExceed (files, fileList) {
      this.$message(`最多可上传${this.limit}个附件`);
    },
    handleError () {
      this.loading = false;
    },
    handleOnChange (file, fileList) {
      this.loading = true
      if (file.percentage == 100) {
        this.loading = false
      }

    },
    handleSuccess ({ code, data, message }, file, fileList) {
      // this.loading = false
      if (code !== 0) {
        this.deleteFile(fileList, fileList.length - 1);
        return this.$message.error(message);
      }
      if (this.requestUrl) {
        data = [{ ...data, fileName: data.name, fileUrl: data.url }]
      }

      if (data.length + this.attachList.length > this.uploadLength) return;
      this.putFileLength += data.length;
      data.forEach((res) => {
        if (this.separate) {
          return this.attachList.push({
            name: res.fileName,
            url: res.fileUrl
          });
        }
        if (this.isCreateOrder) {
          return this.attachList.push({
            name: file.name,
            url: res[0]
          });
        }
        if (res.fileUrl.indexOf("@1") !== -1)
          res.fileUrl = res.fileUrl.split("@1").join("");
        if (this.isCreate) {
          res.fileName = res.fileName.slice(0, res.fileName.indexOf("."));
        }
        this.attachList.push({
          name: res.fileName,
          url: res.fileUrl,
          id: res.id
        });
      });
      if (this.isCover) this.fileTypePic(this.attachList);
      this.$emit("handleUpload", this.attachList);
    },
    fileTypePic (arr) {
      this.attachList = [];

      arr.forEach((res) => {
        let imgUrl = "";
        if (res?.url) res.attachUrl = res.url;
        if (res?.name) res.attachName = res.name;

        const limit = this.isContract
          ? res?.attachName?.substr(res?.attachName?.lastIndexOf(".") + 1)
          : res?.attachUrl?.substr(res?.attachUrl?.lastIndexOf(".") + 1);

        const fileType = Object.entries(this.fileedTypes).find(([type, { suffixes }]) =>
          suffixes.some((e) => this.caseLimit(e, limit))
        )?.[0];

        imgUrl = fileType === "image" ? res.attachUrl : this.fileedTypes[fileType]?.icon || "";

        const files = {
          attachName: res.attachName,
          attachUrl: res.attachUrl,
          imgUrl
        };

        if (this.isCreate) {
          files.attachId = res.attachId || "";
        } else {
          files.id = res.id;
        }
        const imgType = ["png", "img", "jpg", "jpeg"];
        const filterItem = this.intercept(files.attachUrl);
        files.type = imgType.includes(filterItem) ? "picture" : "file";
        // files.srcList = files.type === "picture" ? [files.imgUrl || files.url] : [];

        this.attachList.push(files);
      });
    },
    deleteFile (arr, index) {
      if (arr.length) {
        arr.splice(index, 1);
      }
      this.$emit("update:attachForm", this.attachList);
      this.isDisabled = false;
    },
    intercept (url) {
      return url.substring(url.lastIndexOf('.') + 1);
    }
  }
};
</script>

<style lang="scss" scoped>
.upload-box {
  display: inline-block;
}
.upload-pic {
  ::v-deep .el-upload--text {
    border: 1px dashed var(--prev-border-color-grey);
  }
}
.upload-text {
  margin-left: 10px;
  color: var(--prev-icon-color-orange);
}
.avatar-uploader-icon {
  width: 140px !important;
  height: 140px !important;
  line-height: 140px !important;
}
.noUpload {
  cursor: not-allowed;
}
</style>